<script setup lang="ts">
import type { Socket } from 'socket.io-client';
import { io } from 'socket.io-client';
import { onMounted, onUnmounted, ref, nextTick } from 'vue';
import { baseURL } from '@/utils/http';
import { useUserStore } from '@/stores/user';
import { useRoute } from 'vue-router';
import RoomStatus from './RoomStatus.vue';
import RoomMessage from './RoomMesage.vue';
import RoomAction from './RoomAction.vue';
import type { Message, TimeMessages } from '@/types/room';
import type { Data } from '@/types/user';
import { MsgType, OrderType } from '@/enums';
import dayjs from 'dayjs';
// 请求问诊订单
import type { ConsultOrderItem } from '@/types/consult';
import { getConsultOrderDetail } from '@/services/consult';
import { Toast } from 'vant';

// 消息列表
const list = ref<Message[]>([]);

// 创建实例
const userStore = useUserStore();
const route = useRoute();
let socket: Socket;
// 在组件加载完毕后建立socket链接
onMounted(async () => {
  socket = io(baseURL, {
    auth: {
      // 认证用户
      token: `Bearer ${userStore.user?.token}`,
    },
    query: {
      // 和谁聊天
      orderId: route.query.orderId,
    },
  });
  // 建立连接成功
  socket.on('connect', () => {
    console.log('socket 连接成功');
    // 建立连接后清空聊天记录
    // 场景：如果离开当前页面很久，websocket可能会断开连接。再回到当前页面清空列表加载最新的消息
    list.value = [];
  });
  // 错误信息
  socket.on('error', () => {
    console.log('error 错误信息');
  });
  // 断开连接
  socket.on('disconnect', () => {
    console.log('disconnect 断开成功');
  });
  // 聊天记录（默认信息）
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log(data);
    const arr: Message[] = [];
    data.forEach((item, i) => {
      // 初始化下次请求时间
      if (i === 0) {
        time.value = item.createTime;
      }
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime,
      });
      arr.push(...item.items);
    });
    list.value.unshift(...arr);
    // 取消下拉加载效果
    loading.value = false;
    console.log('页面需要的响应式list数据', list.value);
    // 没有新信息返回 表示加载完毕
    if (data.length === 0) {
      return Toast('没有更早的信息了');
    }
    // 判断是第一次请求的数据还是后来加载更多的数据
    nextTick(() => {
      if (firstLoadMsg.value) {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id);
        window.scrollTo(0, document.body.scrollHeight);
        firstLoadMsg.value = false;
      }
    });
  });
  // 订单状态 在onMounted注册
  socket.on('statusChange', async () => {
    const data = await getConsultOrderDetail(route.query.orderId as string);
    consult.value = data;
  });
  // 接收服务器端消息
  socket.on('receiveChatMsg', async (event: Message) => {
    console.log('接收服务器端消息', event);
    list.value.push(event);
    // UI 体验优化
    await nextTick();
    socket.emit('updateMsgStatus', event.id);
    window.scrollTo(0, document.body.scrollHeight);
  });
});
// 问诊订单
const consult = ref<ConsultOrderItem>();
// 组件加载，生命周期函数可以多次定义。多次定义同名的生命周期函数相当于最后的合并效果
onMounted(async () => {
  // 获取订单详情数据
  const data = await getConsultOrderDetail(route.query.orderId as string);
  console.log(data);
  consult.value = data;
});
// 发送消息到服务器
const sendText = (text: string) => {
  // 发送文字信息需要  发送人  收消息人  消息类型  消息内容
  console.log('====', text);
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text },
  });
};
// 发送图片消息到服务器
const sendImage = (img: { id: string; url: string }) => {
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img },
  });
};
// 是否请求数据的效果
const loading = ref(false);
// 请求数据时间段的开始时间
const time = ref(dayjs().format('YYY-MM-DD HH:mm:ss'));
// 是否是第一次加载聊天记录
const firstLoadMsg = ref(true);
// 下拉页面相关事件处理函数
const onRefresh = () => {
  // 触发下拉请求数据的事件处理函数的时候会把loading改为true
  console.log('用户下拉了', loading);
  // 请求更早聊天记录：条数、时间、订单id
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId);
};

// 组件卸载时断开连接
onUnmounted(() => {
  socket.close();
});
</script>

<template>
  <div class="room">
    <div class="room">
      <CpNavBar title="问诊室" />
      <!-- 添加页面下拉事件支持组件 -->

      <RoomStatus :status="consult?.status" :countdown="consult?.countdown" />
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <RoomMessage :list="list" />
      </van-pull-refresh>
      <!-- 只要不是咨询中就禁用 -->
      <RoomAction
        @send-image="sendImage"
        :disabled="consult?.status !== OrderType.ConsultChat"
        @send-text="sendText"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.room {
  padding-top: 50px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
